﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Celeriq.Graphing.Core;
using System.IO;
using Celeriq.Graphing.Core.Compiling;
using Celeriq.Graphing.Core.Compiling.Generators.InterfaceProject;
using Celeriq.Graphing.Core.Compiling.Generators.ServiceProject;

namespace Celeriq.ServiceGeneratorUtility
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length != 2)
			{
				Console.WriteLine("This application requires two parameters: a repository file and a destination path.");
				Console.WriteLine();
				Console.WriteLine("Press <ENTER> to exit...");
				Console.ReadLine();
				return;
			}

			var repositoryFile = args[0];
			var destinationpath = args[1];

			if (!File.Exists(repositoryFile))
			{
				Console.WriteLine("This repository file does not exist.");
				Console.WriteLine();
				Console.WriteLine("Press <ENTER> to exit...");
				Console.ReadLine();
				return;
			}

			if (!Directory.Exists(destinationpath))
			{
				Console.WriteLine("This destination path does not exist.");
				Console.WriteLine();
				Console.WriteLine("Press <ENTER> to exit...");
				Console.ReadLine();
				return;
			}

			RepositoryDefinition repository = null;

			try
			{
				repository = RepositoryDefinition.FromDisk(repositoryFile);
			}
			catch (Exception ex)
			{
				Console.WriteLine("This repository file is not valid or could not be loaded.");
				Console.WriteLine();
				Console.WriteLine("Press <ENTER> to exit...");
				Console.ReadLine();
				return;
			}

			var executePath = (new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)).DirectoryName;

			var references = new List<string>();
			references.Add(Path.Combine(executePath, "Celeriq.Common.dll"));
			references.Add(Path.Combine(executePath, "Celeriq.Utilities.dll"));
			references.Add(Path.Combine(executePath, "log4net.dll"));

			//Gen the Interfaces
			Generator generator1 =
				new InterfaceProjectGenerator(
					repository,
					destinationpath,
					"Celeriq.API." + repository.GetNamespaceID() + ".Interfaces",
					executePath, 
					references);
			generator1.Generate();

			//Add new assembly to references
			var assemblyName = generator1.ProjectName + ".dll";
			var assemblyPath = System.IO.Path.Combine(generator1.DestinationPath, assemblyName);
			references.Add(assemblyPath);

			//Gen the Interfaces
			Generator generator2 =
				new ServiceProjectGenerator(
					repository,
					destinationpath,
					"Celeriq.API." + repository.GetNamespaceID() + ".Services",
					executePath,
					references);
			generator2.Generate();

			Console.WriteLine("Repository file processed: " + repositoryFile);
			Console.WriteLine("The binaries have been build to the folder: " + destinationpath);
			Console.WriteLine();
			Console.WriteLine("Press <ENTER> to exit...");
			Console.ReadLine();

		}

	}
}
